# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface

from components.pipelines.public.mysql_pipeline import MysqlPipeline


class PatentPipeline(MysqlPipeline):

    def add_company_name(self, _company_name):
        self.to_db.add_smart(
            "net_patent_company_info", {"company_name": _company_name}, update_columns=['company_name']
        )

    def process_item(self, item, spider):
        item.pre_to_db()
        update_list = []
        if item.table_name == 'net_patent_pro_rows':
            if 'applicant_name' in item:
                for company_name in (item['applicant_name'] or []):
                    new_item = item.to_dict
                    self.add_company_name(company_name)
                    new_item['applicant_name_one'] = company_name
                    update_list.append(new_item)
            else:
                update_list.append(item.to_dict)
            if update_list:
                self.update_items(item.table_name, update_list, item.__update_key__)
        else:
            update_list.append(item.to_dict)
            self.update_items(item.table_name, update_list, item.__update_key__)
        return item
